<template>
  <PageWrapper>
    <div class="manage-authority">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane :key="itemData.appId" :tab="itemData.appName" v-for="itemData in allAuthList">
          <div class="authority-header" v-auth="permissionCodeMap.authorityAdd">
            <a-button type="primary" @click="operateAuthority(operateActionType.ADD)">新增权限</a-button>
          </div>
          <div class="authority-list">
            <div class="list-name">名称</div>
            <div class="list-item">类型</div>
            <div class="list-item">操作</div>
          </div>
          <div
            class="authority-tree"
            :style="{ height: 'calc(100vh - 400px)', minHeight: '300px' }"
            v-loading="loading"
          >
            <ScrollContainer>
              <a-tree
                :selectable="false"
                blockNode
                :tree-data="itemData.authorityDetailList"
                ref="treeEle"
                :fieldNames="{
                  title: 'authorityName',
                  key: 'authorityId'
                }"
              >
                <template #title="item">
                  <div class="tree-list">
                    <div class="list-name">{{ item.authorityName }}</div>
                    <div class="list-item">{{ typeMap[item.authorityType] }}</div>
                    <div class="list-item">
                      <a-button
                        type="link"
                        class="g-operate-btn"
                        v-auth="permissionCodeMap.authorityEdit"
                        @click="operateAuthority(operateActionType.EDIT, item)"
                      >
                        编辑
                      </a-button>
                      <a-button
                        type="link"
                        danger
                        class="g-operate-btn"
                        v-auth="permissionCodeMap.authorityDel"
                        @click="authorityDel(item)"
                      >
                        删除
                      </a-button>
                    </div>
                  </div>
                </template>
              </a-tree>
            </ScrollContainer>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
    <AuthorityAdd @register="authorityAddRegister" @operateSuccess="getAuthList" />
    <AuthorityDel @register="authorityDelRegister" @operateSuccess="getAuthList" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, computed, onMounted } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import Empty from '@/components/Empty/index.vue'
import AuthorityAdd from './components/AuthorityAdd.vue'
import AuthorityDel from './components/AuthorityDel.vue'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { treeFilter } from '@/utils/treeHelper'
import { userStore } from '@/store/modules/user'
import { AuthorityRecord } from '@/types/system'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import { SearchOutlined } from '@ant-design/icons-vue'
import ScrollContainer from '@/components/ScrollContainer/index.vue'
import api from '@/api'

const userModule = userStore()

const activeKey = ref('')
const treeEle = ref(null)
const loading = ref(false)

const typeMap: any = {
  0: '菜单',
  1: '按钮',
  2: '应用'
}

const [authorityAddRegister, { openDrawer: authorityAddOpenDrawer, setDrawerProps }] = useDrawer()
const [authorityDelRegister, { openModal: authorityDelOpenModal }] = useModal()

const getAuthList = async () => {
  // 查询权限列表
  loading.value = true
  try {
    await userModule.getRoleAuthList()
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}

const allAuthList: any = computed(() => userModule.allAuthList)

onMounted(async () => {
  await getAuthList()
  if (unref(allAuthList) && unref(allAuthList).length) {
    activeKey.value = unref(allAuthList)[0].appId
  }
})
// 数据筛选及禁用
const treeDataHandle = (list: any[], currentId?: string) => {
  return list
    .filter((item) => {
      return item.authorityType !== 1
    })
    .map((item) => {
      item = Object.assign({}, item)
      if (currentId && item.authorityId === currentId) {
        item.disabled = true
      }
      if (item.children && item.children.length) {
        item.children = treeDataHandle(item.children, currentId)
      }
      return item
    })
}
// 权限信息操作弹框
const operateAuthority = (type: OperateType, record?: AuthorityRecord) => {
  setDrawerProps({
    title: operateTxtType[type]
  })
  let treeData: any[] = []
  if (unref(allAuthList) && unref(allAuthList).length) {
    unref(allAuthList).forEach((item: any) => {
      if (item.appId === unref(activeKey)) {
        // treeData = treeFilter(
        //   item.authorityDetailList,
        //   (item) => {
        //     return item.authorityType !== 1
        //   },
        //   {
        //     key: 'authorityId',
        //     title: 'authorityName'
        //   }
        // )
        treeData = treeDataHandle(
          cloneDeep(item.authorityDetailList),
          operateActionType.EDIT === type ? record?.authorityId : ''
        )
        treeData = [
          {
            authorityId: '0',
            authorityName: item.appName,
            children: treeData
          }
        ]
      }
    })
  }
  authorityAddOpenDrawer(true, {
    type,
    treeData,
    appId: unref(activeKey),
    record
  })
}
const authorityDel = (record: AuthorityRecord) => {
  if (record.children && record.children.length) {
    message.warning('请先删除下级权限')
  } else {
    authorityDelOpenModal(true, {
      record
    })
  }
}
</script>

<style lang="less" scoped>
.authority-header {
  margin-bottom: 32px;
  display: flex;
  align-items: center;
  .header-search {
    width: 260px;
    margin-right: 24px;
  }
}
.authority-list {
  width: 100%;
  border-bottom: 1px solid #e8e8e8;
  padding: 0 4px 16px 8px;
  display: flex;
  .list-item {
    width: 260px;
  }
  .list-name {
    flex: 1;
  }
}
.authority-tree {
  padding-top: 16px;
  position: relative;
  overflow-y: auto;
  .tree-list {
    width: 100%;
    display: flex;
    align-items: center;
    .list-item {
      width: 260px;
      :deep(.ant-btn) {
        padding: 0;
        height: 24px;
        font-size: 14px;
      }
    }
    .list-name {
      flex: 1;
    }
  }
}
</style>
